package com.yonyou.pmclouds.plan.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.plan.entity.ProjectPlanViewVO;
import com.yonyou.pmclouds.plan.rmiitf.ProjectPlanQuery;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Controller
@RequestMapping(value = "/plan")
@Deprecated
public class PlanBoardController {


    @Autowired
    private UserInfoQuery userInfoQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectPlanQuery projectPlanQuery;

    private static final String[] USER_ID_FIELDS = {ProjectVO.MANAGER,ProjectVO.CREATOR};
    private static final String[] USER_NAME_FIELDS = {ProjectVO.MANAGER_NAME,ProjectVO.CREATOR_NAME};

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectSimpleQuery query;

    @GetMapping("/queryBoardByPkProSrc")
    @ResponseBody
    public Map<String,Object> queryBoardByPkProSrc(@RequestParam("pkSrc") String pkProSrc) throws BusinessException {

        Map<String, Object> result = query.queryPlanBoardByProSrcId(pkProSrc);
        if(result == null || result .size() == 0 ){
            return new HashMap<>();
        }

        ProjectVO projectVO = (ProjectVO)result.get("projectVO");
        ProjectPlanViewVO[] projectPlanVOS = (ProjectPlanViewVO[])result.get("projectPlanVOS");

        Map<String, List<ProjectPlanViewVO>> childMap = genChildMap(projectPlanVOS);
        List<ProjectPlanViewVO> treeList = childMap.get(StringUtils.EMPTY);
        if (treeList != null) {
            //计算进度
            setProcess(null,treeList);
            //剔除所有的孩子集  在这里没有必要要孩子
            for (ProjectPlanViewVO projectPlanViewVO : treeList) {
                projectPlanViewVO.setChild(null);
            }
            projectVO.setProjectPlanVOS(treeList.toArray(new ProjectPlanViewVO[0]));
            projectVO.setProgress(treeList.get(0).getProgress());
            result.remove("projectPlanVOS");
        }

        userInfoQuery.tranUserInfoField(new Object[]{projectVO}, USER_ID_FIELDS, USER_NAME_FIELDS);

        return result;
    }

    /**
     *
     * @param projectId
     * @return  根据项目id 返回项目看板数据
     */
    @GetMapping("/projectById")
    @ResponseBody
    public Map<String,Object> queryProjectById(@RequestParam("projectId") String projectId,@RequestParam(required = false,name="pkPlan") String pkPlan) throws BusinessException {

        Map<String, Object> result = query.queryProjectKanbanById(projectId,pkPlan);
        if(result == null) return new HashMap<String,Object>();

        ProjectVO projectVO = (ProjectVO)result.get("projectVO");
        ProjectPlanViewVO[] projectPlanVOS = (ProjectPlanViewVO[])result.get("projectPlanVOS");

        Map<String, List<ProjectPlanViewVO>> childMap = genChildMap(projectPlanVOS);
        List<ProjectPlanViewVO> treeList = childMap.get(StringUtils.EMPTY);
        if (treeList != null) {
            //计算进度
            setProcess(null,treeList);
            //剔除所有的孩子集  在这里没有必要要孩子
            for (ProjectPlanViewVO projectPlanViewVO : treeList) {
                projectPlanViewVO.setChild(null);
                if(StringUtils.isEmpty(pkPlan)){
                    projectVO.setProjectPlanVOS(treeList.toArray(new ProjectPlanViewVO[0]));
                    projectVO.setProgress(treeList.get(0).getProgress());
                    break;
                }else{
                    if(pkPlan.equals(projectPlanViewVO.getPkPlan())){
                        projectVO.setProgress(projectPlanViewVO.getProgress());
                        break;
                    }
                }
            }
            result.remove("projectPlanVOS");
        }

        userInfoQuery.tranUserInfoField(new Object[]{projectVO}, USER_ID_FIELDS, USER_NAME_FIELDS);

        return result;
    }

    @RequestMapping("/getMillstones")
    @ResponseBody
    public  ProjectPlanViewVO[] getMillstones(@RequestParam("projectId")String projectId,@RequestParam("pkPlan") String pkPlan) throws BusinessException{

        ProjectPlanViewVO[] projectPlanViewVOS = projectPlanQuery.queryMilltStonePlanByPkProject(projectId, pkPlan);

        return projectPlanViewVOS;
    }

    private Map<String, List<ProjectPlanViewVO>> genChildMap(ProjectPlanViewVO[] allVOs) {

        // 构造树
        Map<String, List<ProjectPlanViewVO>> childMap = new HashMap<>();
        if(ArrayUtils.isEmpty(allVOs))
            return childMap;

        for (ProjectPlanViewVO vo : allVOs) {
            String parent = vo.getPkParent();
            if (StringUtils.isEmpty(parent)) {
                parent = StringUtils.EMPTY;
            }
            List<ProjectPlanViewVO> children = childMap.get(parent);
            if (children == null) {
                children = new ArrayList<>();
                childMap.put(parent, children);
            }
            children.add(vo);
        }
        for (ProjectPlanViewVO vo : allVOs) {
            vo.setScode(null);
        }
        for (ProjectPlanViewVO vo : allVOs) {
            List<ProjectPlanViewVO> children = childMap.get(vo.getPkPlan());
            if (children != null) {
                vo.setChild(children.toArray(new ProjectPlanViewVO[0]));
            }
        }

        return childMap;
    }

    //计算进度
    public void setProcess(ProjectPlanViewVO parent, List<ProjectPlanViewVO> tree){
        if(tree == null || tree.isEmpty())  return;
        int childAvg = 0;
        int days = 0;
        for (ProjectPlanViewVO projectPlanViewVO : tree) {
            List<ProjectPlanViewVO> childList = projectPlanViewVO.getChild() == null ? new ArrayList<ProjectPlanViewVO>() : Arrays.asList(projectPlanViewVO.getChild());
            setProcess(projectPlanViewVO,childList);
            //因为默认结束时间为当天结束 所以天数+1
            int day = getDayDiffer(projectPlanViewVO.getExpeStartDate(),projectPlanViewVO.getExpeEndDate())+1;
            days+=day;
            childAvg += projectPlanViewVO.getProgress() * day;
        }
        if(parent != null) parent.setProgress(childAvg/days);
    }

    public static int getDayDiffer(Date startDate, Date endDate) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long startDateTime = 0,endDateTime = 0;
        try {
            startDateTime = dateFormat.parse(dateFormat.format(startDate)).getTime();
            endDateTime = dateFormat.parse(dateFormat.format(endDate)).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (int) ((endDateTime - startDateTime) / (1000 * 3600 * 24));
    }

}
